import React, { useState } from "react";
import {
  Modal,
  Form,
  Input,
  Button,
  Select,
  Upload,
  Avatar,
  Row,
  Col,
  Space,
} from "antd";
import {
  PhoneOutlined,
  MailOutlined,
  CameraOutlined,
  UserAddOutlined,
} from "@ant-design/icons";
import { useAuth } from "../contexts/AuthContext";
import { useTheme } from "../contexts/ThemeContext";
import type { RegisterForm } from "../types/user";

interface RegisterModalProps {
  open: boolean;
  onCancel: () => void;
}

const RegisterModal: React.FC<RegisterModalProps> = ({ open, onCancel }) => {
  const { register, loading } = useAuth();
  const { theme } = useTheme();
  const [form] = Form.useForm();
  const [avatar, setAvatar] = useState<string>("");

  const handleRegister = async (values: RegisterForm) => {
    const success = await register({ ...values, avatar });
    if (success) {
      form.resetFields();
      setAvatar("");
      onCancel();
    }
  };

  const handleCancel = () => {
    form.resetFields();
    setAvatar("");
    onCancel();
  };

  const handleAvatarChange = (info: {
    file: { status?: string; originFileObj?: File };
  }) => {
    if (info.file.status === "done" || info.file.originFileObj) {
      const reader = new FileReader();
      reader.onload = (e) => {
        setAvatar(e.target?.result as string);
      };
      if (info.file.originFileObj) {
        reader.readAsDataURL(info.file.originFileObj);
      }
    }
  };

  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith("image/");
    if (!isImage) {
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      return false;
    }
    return false; // 阻止自动上传，我们手动处理
  };

  return (
    <Modal
      open={open}
      onCancel={handleCancel}
      footer={null}
      width={600}
      centered
      className="register-modal"
      title={null}
      closable={false}
      zIndex={9999}
      mask={true}
      maskClosable={true}
      destroyOnHidden={true}
    >
      <div className="register-modal-container">
        {/* 固定的标题区域 */}
        <div className="register-modal-header">
          <div className="text-center">
            <UserAddOutlined
              className="mr-2 text-2xl"
              style={{ color: theme.colors.primary[500] }}
            />
            <h3
              className="text-xl font-semibold inline-block"
              style={{ color: theme.colors.primary[600] }}
            >
              创建新账号
            </h3>
          </div>
          <p className="text-center text-gray-500 mt-2 mb-0">
            填写信息创建您的账号
          </p>
        </div>

        {/* 可滚动的表单区域 */}
        <div className="register-modal-body">
          <Form
            form={form}
            name="register"
            onFinish={handleRegister}
            layout="vertical"
            size="large"
          >
            {/* 头像上传 */}
            <Form.Item label="头像" className="text-center mb-4">
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                beforeUpload={beforeUpload}
                onChange={handleAvatarChange}
              >
                {avatar ? (
                  <Avatar size={56} src={avatar} />
                ) : (
                  <div>
                    <CameraOutlined
                      style={{
                        fontSize: "18px",
                        color: theme.colors.primary[500],
                      }}
                    />
                    <div style={{ marginTop: 4, fontSize: "11px" }}>
                      上传头像
                    </div>
                  </div>
                )}
              </Upload>
            </Form.Item>

            {/* 账号和姓名 */}
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="username"
                  label="账号"
                  rules={[
                    { required: true, message: "请输入账号!" },
                    { min: 3, message: "账号至少3个字符!" },
                    {
                      pattern: /^[a-zA-Z0-9_]+$/,
                      message: "账号只能包含字母、数字和下划线!",
                    },
                  ]}
                >
                  <Input placeholder="请输入账号" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="姓名"
                  rules={[{ required: true, message: "请输入姓名!" }]}
                >
                  <Input placeholder="请输入姓名" />
                </Form.Item>
              </Col>
            </Row>

            {/* 密码 */}
            <Form.Item
              name="password"
              label="密码"
              rules={[
                { required: true, message: "请输入密码!" },
                { min: 6, message: "密码至少6个字符!" },
              ]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>

            {/* 确认密码 */}
            <Form.Item
              name="confirmPassword"
              label="确认密码"
              dependencies={["password"]}
              rules={[
                { required: true, message: "请确认密码!" },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue("password") === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error("两次输入的密码不一致!"));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请再次输入密码" />
            </Form.Item>

            {/* 性别和手机号 */}
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="gender"
                  label="性别"
                  rules={[{ required: true, message: "请选择性别!" }]}
                >
                  <Select placeholder="请选择性别">
                    <Select.Option value="male">男</Select.Option>
                    <Select.Option value="female">女</Select.Option>
                    <Select.Option value="other">其他</Select.Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="phone"
                  label="手机号"
                  rules={[
                    { required: true, message: "请输入手机号!" },
                    {
                      pattern: /^1[3-9]\d{9}$/,
                      message: "请输入正确的手机号!",
                    },
                  ]}
                >
                  <Input
                    prefix={<PhoneOutlined />}
                    placeholder="请输入手机号"
                  />
                </Form.Item>
              </Col>
            </Row>

            {/* 邮箱 */}
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: "请输入邮箱!" },
                { type: "email", message: "请输入正确的邮箱格式!" },
              ]}
            >
              <Input prefix={<MailOutlined />} placeholder="请输入邮箱" />
            </Form.Item>
          </Form>
        </div>

        {/* 固定的按钮区域 */}
        <div className="register-modal-footer">
          <Space className="w-full">
            <Button onClick={handleCancel} className="flex-1" size="large">
              取消
            </Button>
            <Button
              type="primary"
              onClick={() => form.submit()}
              loading={loading}
              className="flex-1"
              size="large"
              style={{
                backgroundColor: theme.colors.primary[500],
                borderColor: theme.colors.primary[500],
              }}
            >
              注册
            </Button>
          </Space>
        </div>
      </div>
    </Modal>
  );
};

export default RegisterModal;
